import json
import random
import re
import time
from hashlib import md5
import ast
import docx
import requests

# 加载自定义翻译数据
with open('data.json', 'r', encoding="UTF-8") as f:
    myData = json.load(f)
# 特殊字符
specialCharacters = ['↓', '--']

# 是否为数学公式
def is_math_expression(s):
    try:
        ast.parse(s)
        return True
    except SyntaxError:
        return False


# 是否由数字和特殊字符组成
def is_valid_string(s):
    # 定义特殊字符集合，这里假设特殊字符为!@#$%^&*()
    special_chars = r"!@#$%^&*()≤"

    # 创建正则表达式模式
    pattern = re.compile(rf"^[0-9{re.escape(special_chars)}]+$")

    # 检查字符串是否匹配模式
    return bool(pattern.match(s))


# 是否为中文
def is_chinese(text):
    # 使用正则表达式匹配中文字符
    pattern = re.compile(r'[\u4e00-\u9fff]+')
    return bool(pattern.search(text))


# 是否为纯数字
def is_number_regex(s):
    pattern = re.compile(r'^[-+]?[0-9]*\.?[0-9]+$')
    return bool(pattern.match(s))


def fanyi(query):
    # 0.过滤前后空格
    query = query.strip()
    # 0.空字符，不进行翻译
    if not query:
        print("空字符串，不进行翻译", query)
        return query
    # 0.判断是纯数字,不需要翻译
    if is_number_regex(query):
        print("纯数字，不进行翻译", query)
        return query
    # 0.特殊字符不需要翻译
    if query in specialCharacters:
        print("特殊字符，不进行翻译", query)
        return query
    # 0.判读是中文不需要翻译
    if is_chinese(query):
        print("中文字符，不进行翻译", query)
        return query
    # 1.使用本地翻译
    if query in myData:
        print('使用本地翻译', query)
        print('使用本地翻译结果：', myData[query])
        return myData[query]
    # 2.使用百度翻译
    # Set your own appid/appkey.
    appid = '20231020001853827'
    appkey = 'vpjD5ti_efOUikC3ax2p'
    # appkey = 'vpjD5ti_efOUikC3ax2pddd'

    # For list of language codes, please refer to `https://api.fanyi.baidu.com/doc/21`
    from_lang = 'en'
    to_lang = 'zh'

    endpoint = 'http://api.fanyi.baidu.com'
    path = '/api/trans/vip/translate'
    url = endpoint + path

    # Generate salt and sign
    def make_md5(s, encoding='utf-8'):
        return md5(s.encode(encoding)).hexdigest()

    salt = random.randint(32768, 65536)
    sign = make_md5(appid + query + str(salt) + appkey)

    # Build request
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    payload = {'appid': appid, 'q': query, 'from': from_lang, 'to': to_lang, 'salt': salt, 'sign': sign}
    print("使用百度翻译：", payload)
    # Send request
    r = requests.post(url, params=payload, headers=headers)
    respResult = r.json()
    if 'error_code' in respResult:
        print("翻译失败：", respResult['error_msg'])
        return query
    else:
        result = ""
        for index, item in enumerate(respResult['trans_result']):
            # 检查是否是最后一次循环之前的循环
            if index < len(respResult['trans_result']) - 1:
                result = result + item['dst'] + "\n"
            else:
                result = result + item['dst']
        print("使用百度翻译结果:", result)
        return result


# 目标文档
doc = docx.Document("input6.docx")

# 记录开始时间
start_time = time.time()
# 段落
p_list = doc.paragraphs
for p in p_list:
    print(p.text)
    # 进行非空判断，进行修改
    p.text = fanyi(p.text)
# 表格
table_list = doc.tables
for table in table_list:
    x = []
    for row in table.rows:
        y = []
        for cell in row.cells:
            y.append(cell.text)
            # 进行翻译
            cell.text = fanyi(cell.text)
        x.append(y)
    # print(x)
    # print("---")

# 页眉和页脚
for section in doc.sections:
    # 获取页脚
    footer = section.footer
    header = section.header
    # 如果页脚存在，则遍历页脚中的所有段落（paragraph）
    if footer:
        for paragraph in footer.paragraphs:
            # 打印段落中的文本内容
            if paragraph.text:
                paragraph.text = fanyi(paragraph.text)
            tables = footer.tables
            for table in tables:
                x = []
                for row in table.rows:
                    y = []
                    for cell in row.cells:
                        y.append(cell.text)
                        # 进行翻译
                        cell.text = fanyi(cell.text)
                    x.append(y)
    if header:
        for paragraph in header.paragraphs:
            # 打印段落中的文本内容
            paragraph.text = fanyi(paragraph.text)
        tables = header.tables
        for table in tables:
            x = []
            for row in table.rows:
                y = []
                for cell in row.cells:
                    y.append(cell.text)
                    # 进行翻译
                    cell.text = fanyi(cell.text)
                x.append(y)

doc.save("output6.docx")
# 记录结束时间
end_time = time.time()
# 计算运行时间
execution_time = end_time - start_time
print(f"程序运行时间: {execution_time:.5f} 秒")
print("翻译完成")
